import axios from 'axios';
import { appId, baseURL, mobileMsProvider, userAuthMsUrl } from '../constants';
import { getValue } from './asyncStorage';
import LogoutPrompt from '@/screens/Login/logoutPrompt';

const instance = axios.create({
  baseURL,
  timeout: 25000,
});

//请求拦截处理
instance.interceptors.request.use(
  async (config) => {
    const netinfo = await getValue('netinfo');
    const deviceinfo = await getValue('deviceinfo');
    //const geolocation = await getValue('geolocation');
    const fingerprint = { ...netinfo, ...deviceinfo };
    //if (geolocation.enabled) {
    //  delete geolocation.enabled;
    //  fingerprint = {...fingerprint, ...geolocation};
    //}
    config.headers = {
      ...config.headers,
      AppId: appId,
      AppFingerprint: JSON.stringify(fingerprint),
    };
    let changeBaseUrl;
    if (
      config.url.indexOf('auth/oauth/token') === -1 &&
      config.url.indexOf('auth/gjopenid/token') === -1
    ) {
      const authToken = await getValue('auth_token');
      if (authToken) {
        config.headers.Authorization = `Bearer ${authToken.access_token}`;
      }
      if (
        config.url.indexOf('user/') !== 0 &&
        config.url.indexOf('FileHandler/') !== 0
      ) {
        config.baseURL = `${config.baseURL}${mobileMsProvider}/`;
      } else if (config.url.indexOf('user/') === 0) {
        changeBaseUrl = true;
      }
    } else {
      changeBaseUrl = true;
    }
    if (changeBaseUrl && userAuthMsUrl) {
      config.baseURL = userAuthMsUrl;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

//返回拦截处理
instance.interceptors.response.use(
  function (response) {
    //console.log(JSON.stringify(response, null, 2));
    if (response.data) {
      if (!response.data.ErrorCode) {
        if (response.data.Result) {
          if (
            Object.keys(response.data.Result).length === 2 &&
            Object.keys(response.data.Result).includes('jsonResult') &&
            Object.keys(response.data.Result).includes('loginUser')
          ) {
            return { data: JSON.parse(response.data.Result.jsonResult) };
          }
          return { data: response.data.Result };
        }
        return { data: response.data };
      } else {
        console.log(
          'axios response return ErrorCode',
          JSON.stringify(response, null, 2),
        );
        let errorMsg =
          response.data.Message ||
          `后台服务返回错误,错误代码${response.data.ErrorCode}`;
        if (
          response.data.ErrorCode === 1000 &&
          (!response.data.Message ||
            `Bearer ${response.data.Message}` ===
              response.config.headers.Authorization)
        ) {
          errorMsg = '后台服务请求凭证已失效, 请退出重新登录';
          LogoutPrompt();
          return {
            errorCode: 0,
            errorMsg: '',
            data: [],
          };
        }
        return {
          errorCode: response.data.ErrorCode,
          errorMsg,
          data: [],
        };
      }
    }
    return { data: [] };
  },
  function (error) {
    console.log('axios response error', JSON.stringify(error.config, null, 2));
    let errorMsg = error.message;
    let errorCode = error.name;
    if (error.response) {
      errorMsg = `网络请求失败,失败代码${error.response.status}`;
      if (error.response.data && error.response.data.message) {
        errorMsg = error.response.data.message;
      }
      errorCode = error.response.status;
    }
    return {
      errorCode,
      errorMsg,
      data: [],
    };
  },
);

export default instance;
